package com.atom.common.delegate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.atom.common.DelegateStatus;
import com.atom.common.dao.AvensCommonDao;
import com.atom.common.exception.AvensNullPointerException;

@Repository
public class DelegateInfoDao extends AvensCommonDao<DelegateInfo> {

  @SuppressWarnings("unchecked")
  public List<DelegateInfo> getAddDelegateList(Date current) {
    String sql = "FROM DelegateInfo WHERE startTime <= ? AND isCancel = 0 AND delegateStatus = " + DelegateStatus.ADD_UNDO;
    return super.executeQuery(sql, current);

  }

  @SuppressWarnings("unchecked")
  public List<DelegateInfo> getDelDelegateList(Date current) {
    String sql = "FROM DelegateInfo WHERE endTime <= ? ";
    return super.executeQuery(sql, current);
  }

  public DelegateInfo findByAgentByUserByTypeByTime(String agent, String user, int type, String processDefKey, Date beginTime) {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("assignee", agent);
    properties.put("owner", user);
    properties.put("delegateType", type);
    properties.put("processDefinitionKey", processDefKey);
    properties.put("startTime", beginTime);
    List<DelegateInfo> result =  super.findByProperties(properties);
    if (result == null || result.isEmpty()) {
      throw new AvensNullPointerException("cannot find delegateinfo");
    } else {
      return result.get(0);
    }
  }

  @SuppressWarnings("unchecked")
  public DelegateInfo findByUserByPDK(String owner, String processDefinitionKey, Date current) {
    String sql = "FROM DelegateInfo WHERE startTime <= ?"
        + " AND isCancel = 0"
        + " AND owner = '" + owner + "'"
        + " AND delegateStatus = " + DelegateStatus.ADD_DONE
        + " AND processDefinitionKey = '" + processDefinitionKey + "'";
    List<DelegateInfo> result =  super.executeQuery(sql, current);
    if (result == null || result.isEmpty()) {
      return null;
    } else {
      return result.get(0);
    }
  }

}
